package com.itheima.travel.web;

import com.github.pagehelper.PageInfo;
import com.itheima.travel.enums.StatusEnum;
import com.itheima.travel.exception.ProjectException;
import com.itheima.travel.pojo.Route;
import com.itheima.travel.req.RouteVo;
import com.itheima.travel.res.ResponseWrap;
import com.itheima.travel.service.RouteService;
import com.itheima.travel.utils.ExceptionsUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 *
 */
@RestController
@Log4j2
@RequestMapping("/route")
@CrossOrigin
public class RouteController {
    @Autowired
    private RouteService routeService;

    @Value("${upload.webSite}")
    String webSite;

    // 通过id查询线路
    @GetMapping("{routeId}")
    public ResponseWrap<RouteVo> findRouteByEd(@PathVariable("routeId") Long routeId) throws ProjectException {
        try{
        RouteVo routeVo = RouteVo.builder().id(routeId).build();
        RouteVo routeResult = routeService.findRouteById(routeVo);
            return ResponseWrap.<RouteVo>builder()
                    .code(StatusEnum.SUCCEED.getCode())
                    .msg(StatusEnum.SUCCEED.getMsg())
                    .webSite(webSite)
                    .data(routeResult)
                    .operationTime(new Date())
                    .build();
        }catch (Exception e){
            log.error("查询线路:{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(StatusEnum.FIND_ROUTE_ID_FAIL.getCode(),StatusEnum.FIND_ROUTE_ID_FAIL.getMsg());
        }

    }

    @PostMapping("{pageNum}/{pageSize}")
    public ResponseWrap<PageInfo<RouteVo>> findRouteByPage(@RequestBody RouteVo routeVo,
                                                           @PathVariable("pageNum") Integer pageNum,
                                                           @PathVariable("pageSize") Integer pageSize) throws ProjectException {
        try {
            PageInfo<RouteVo> routeByPage = routeService.findRouteByPage(routeVo, pageNum, pageSize);
            return ResponseWrap.<PageInfo<RouteVo>>builder()
                    .code(StatusEnum.SUCCEED.getCode())
                    .msg(StatusEnum.SUCCEED.getMsg())
                    .operationTime(new Date())
                    .webSite(webSite)
                    .data(routeByPage)
                    .build();
        }catch (Exception e){
            log.error("分页查询线路：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(StatusEnum.FIND_ROUTE_PAGE_FAIL.getCode(),
                    StatusEnum.FIND_ROUTE_PAGE_FAIL.getMsg());
        }

    }
}
